<?php

// $Id$


require_once(TANGRA_MAIN_DIR.'interfaces/i_db_storable.class.php');

require_once('visitor_cookie.class.php');


class Visitor_Cookie_DBC extends Visitor_Cookie implements I_DB_Storable {
	public function load_by_id(DB_Connection $dbc, $id) {
		$ret = false;

		$sql = "select cookie ".
							"from visitors_cookies where id = $id";

		$rez = $dbc->execute($sql);

		if (!$rez->is_eof()) {
			$rez_obj = $rez->fetch_object();
			$this->set_id($id);
			$this->set_cookie($rez_obj->COOKIE);

			$ret = $id;
		}

		return $ret;
	}


	public function save(DB_Connection $dbc) {
		$ret = false;

		if ($this->get_id()) {
			$ret = $this->update($dbc);
		} else {
			$ret = $this->insert($dbc);
		}

		return $ret;
	}


	protected function insert(DB_Connection $dbc) {
		$ret = false;

		$id = $dbc->generate_id('visitors_cookies_seq');
		if ($id) {

			$cookie = addslashes($this->get_cookie());

			$sql = "insert into visitors_cookies"
								."(id, "
								."cookie) "
							."values ("
								."$id, "
								."'$cookie');";
			$dbc->execute($sql);

			$this->notify_on_create();
			$this->set_id($id);

			$ret = $id;
		} else {
			throw new TE_Exception('ID not generated - visitors_cookies_seq');
		}

		return $ret;
	}


	protected function update(DB_Connection $dbc) {

		$cookie = addslashes($this->get_cookie());

		$sql = "update visitors_cookies set "
							."cookie = '$cookie' "
					."where id = ".$this->get_id();

		$dbc->execute($sql);
		$this->notify_on_update();

		return $this->get_id();
	}


	public static function generate_new_cookie(DB_Connection $dbc) {
		$loop = true;
		do {
			$md5 = md5(rand());

			$sql = "select id from visitors_cookies where cookie = '$md5'";
			$rez = $dbc->execute($sql);
			if ($rez->is_eof()) {
				$loop = false;
			}
		} while ($loop);


		return $md5;
	}


	public function load_by_cookie(DB_Connection $dbc, $cookie) {
		$ret = false;

		$cookie = addslashes($cookie);
		$sql = "select id from visitors_cookies where cookie = '$cookie'";
		$rez = $dbc->execute($sql);
		if (!$rez->is_eod()) {
			$rez_obj = $rez->fetch_object();
			$ret = $this->load_by_id($dbc, $rez_obj->ID);
		}

		return $ret;
	}


	public static function cookie_exists(DB_Connection $dbc, $cookie) {
		$ret = false;

		$cookie = addslashes($cookie);
		$sql = "select id from visitors_cookies where cookie = '$cookie'";
		$rez = $dbc->execute($sql);
		if (!$rez->is_eod()) {
			$rez_obj = $rez->fetch_object();
			$ret = $rez_obj->ID;
		}


		return $ret;
	}
}

